package com.qiujie.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qiujie.dto.ApproveDTO;
import com.qiujie.dto.Response;
import com.qiujie.entity.ApproveRecord;
import com.qiujie.entity.Staff;
import com.qiujie.entity.StaffDetails;
import com.qiujie.enums.AuditStatusEnum;
import com.qiujie.enums.ErrorEnum;
import com.qiujie.mapper.ApproveRecordMapper;
import com.qiujie.mapper.LeaveMapper;
import com.qiujie.mapper.StaffMapper;
import com.qiujie.service.StaffLeaveService;
import com.qiujie.entity.StaffLeave;

import com.qiujie.dto.ResponseDTO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/staff-leave")
@Log4j2
public class StaffLeaveController {

    @Autowired
    private StaffLeaveService staffLeaveService;

    @Autowired
    private ApproveRecordMapper  approveRecordMapper;

    @Autowired
    private StaffMapper staffMapper;

    @ApiOperation("新增")
    @PostMapping
    public ResponseDTO add(@RequestBody StaffLeave staffLeave) {
        return this.staffLeaveService.add(staffLeave);
    }

    @ApiOperation("逻辑删除")
    @DeleteMapping("/{id}")
    public ResponseDTO delete(@PathVariable Integer id) {
        return this.staffLeaveService.delete(id);
    }

    @ApiOperation("批量逻辑删除")
    @DeleteMapping("/batch/{ids}")
    public ResponseDTO deleteBatch(@PathVariable List<Integer> ids) {
        return this.staffLeaveService.deleteBatch(ids);
    }

    @ApiOperation("编辑更新")
    @PutMapping
    public ResponseDTO edit(@RequestBody StaffLeave staffLeave) {
        return this.staffLeaveService.edit(staffLeave);
    }


    @ApiOperation("查询")
    @GetMapping("/{id}")
    public ResponseDTO query(@PathVariable Integer id) {
        return this.staffLeaveService.query(id);
    }



    @ApiOperation("分页条件查询")
    @GetMapping
    @PreAuthorize("hasAnyAuthority('performance:leave:list','performance:leave:search')")
    public ResponseDTO list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer deptId,
            @RequestParam String code) {  // 注意此处code参数是否允许为空

        System.out.println("接收参数："
                + " current=" + current
                + " size=" + size
                + " name=" + name
                + " deptId=" + deptId
                + " code=" + code);

        return staffLeaveService.list(current, size, name, deptId, code);
    }

    @ApiOperation("数据导出接口")
    @GetMapping("/export/{filename}")
    @PreAuthorize("hasAnyAuthority('performance:leave:export')")
    public void export(HttpServletResponse response,@PathVariable  String filename) throws IOException {
        this.staffLeaveService.export(response,filename);
    }

    @ApiOperation("数据导入接口")
    @PostMapping("/import")
    @PreAuthorize("hasAnyAuthority('performance:leave:import')")
    public ResponseDTO imp(MultipartFile file) throws IOException {
        return this.staffLeaveService.imp(file);
    }


    @ApiOperation("获取所有")
    @GetMapping("/all")
    public ResponseDTO queryAll() {
        return this.staffLeaveService.queryAll();
    }








    // StaffLeaveController.java 修改接口
    @ApiOperation("个人请假记录")
    @GetMapping("/personal")
    @PreAuthorize("hasAnyAuthority('performance:leave:personal')")
    public ResponseDTO listPersonal(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @AuthenticationPrincipal StaffDetails staffDetails) {

        log.info("当前认证用户：{}", staffDetails.getUsername());

        Staff staff = staffMapper.selectOne(
                new QueryWrapper<Staff>().eq("code", staffDetails.getUsername())
        );
        return staffLeaveService.queryByStaffId(current, size, staff.getId());
    }








    @ApiOperation("申请请假")
    @PostMapping("/apply")
    @PreAuthorize("hasAnyAuthority('performance:leave:apply')")
    public ResponseDTO apply(@RequestBody StaffLeave staffLeave,
                             @AuthenticationPrincipal StaffDetails staffDetails) {

        log.info("===== 开始处理请假申请 =====");
        log.info("请求参数：{}", staffLeave);
        log.info("认证用户详情：{}", staffDetails);

        // 直接使用已认证的用户信息
        Staff staff = staffMapper.selectOne(
                new QueryWrapper<Staff>().eq("code", staffDetails.getUsername())
        );

        if (staff == null) {
            log.error("数据库查询结果为空！工号：{}", staffDetails.getUsername());
            return ErrorEnum.STAFF_NOT_FOUND.toResponse();
        }

        log.info("关联员工信息：ID={} 姓名={}", staff.getId(), staff.getName());
        staffLeave.setStaffId(staff.getId());

        ResponseDTO response = staffLeaveService.apply(staffLeave);
        // 确保返回的ResponseDTO包含code字段
        if(response == null){
            log.error("服务层返回空响应！");
            return ErrorEnum.SYSTEM_ERROR.toResponse(); // 使用已定义的错误枚举
        }
        return response;
    }









    @ApiOperation("审批操作")
    @PostMapping("/approve/{leaveId}")
    @PreAuthorize("hasAnyAuthority('performance:leave:approve')")
    public ResponseDTO approve(
            @PathVariable Integer leaveId,
            @RequestBody ApproveDTO dto) {

        try {
            // 参数校验增强
            if (dto.getStatus() == null || !Arrays.asList(1, 2).contains(dto.getStatus())) {
                log.warn("无效审批状态：{}", dto.getStatus());
                return ErrorEnum.STATUS_INVALID.toResponse();
            }
            if (StringUtils.isBlank(dto.getCode())) {
                return ErrorEnum.PARAM_REQUIRED.toResponse("审批人工号");
            }

            // 处理空备注
            String remark = StringUtils.isBlank(dto.getRemark()) ? "无备注信息" : dto.getRemark();

            log.info("审批操作：leaveId={}, status={}, approver={}", leaveId, dto.getStatus(), dto.getCode());
            return staffLeaveService.approve(leaveId, dto.getStatus(), remark, dto.getCode());

        } catch (Exception e) {
            log.error("审批异常：", e);
            return ErrorEnum.SYSTEM_ERROR.toResponse();
        }
    }


    // StaffLeaveController.java 新增接口
    @ApiOperation("待审批列表")
    @GetMapping("/pending")
    @PreAuthorize("hasAnyAuthority('performance:leave:approve')")
    public ResponseDTO listPendingApprovals(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @AuthenticationPrincipal StaffDetails staffDetails) {

        return staffLeaveService.listPendingApprovals(
                current, size, staffDetails.getUsername()
        );
    }


    // StaffLeaveController.java 新增接口
    @ApiOperation("审批记录查询")
    @GetMapping("/records/{leaveId}")
    public ResponseDTO getApproveRecords(@PathVariable Integer leaveId) {
        List<ApproveRecord> records = approveRecordMapper.selectList(
                new QueryWrapper<ApproveRecord>()
                        .eq("leave_id", leaveId)
                        .orderByAsc("create_time")
        );
        return Response.success(records);
    }





}

